package cn.com.bsfit.netty.req;

import cn.com.bsfit.netty.exception.DefaultException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 类名 JsonReqData2Data
 * 描述 将JSON格式的流数据转化为Map
 *
 * @author hedonglin
 * @version 1.0
 * @date 2019/9/27 10:21
 */
@SuppressWarnings("all")
@Component(value = "jsonReqData2Map")
@Slf4j
public class JsonReqData2Map implements ReqData2MapStrategy {
    @Autowired
    private IReqDataFormat jsonReqFormat;

    /**
     * 首部字段
     */
    private ThreadLocal<String> currTopField = new ThreadLocal<String>();

    @Override
    public Map<String, Object> reqData2Map(String msg) throws DefaultException {
        try {
            // 解析为JSON
            Map<String, Object> map = JSONObject.parseObject(msg.trim());
            log.info("将消息转换为JSON数据成功");
            Object o = null;
            if (map != null) {
                // 获取顶层字段
                List<String> topFields = jsonReqFormat.getTopField();
                if (map.size() == 1){
                    // 具有顶层标签
                    for (String key : map.keySet()) {
                        o  = map.get(key);
                        if (o != null && (o instanceof Map)){
                            currTopField.set(key);
                        }
                    }
                }

                if (currTopField.get() == null || currTopField.get() == ""){
                    currTopField.remove();
                }
            }
            // 顶层字段存在，去除顶层字段，获得只包含Head,Body的Map结构
            if (o instanceof Map) {
                map.clear();
                return (Map<String, Object>) o;
            }
            return map;
        } catch (Exception e) {
            throw new DefaultException("将消息转换为JSON数据失败");
        }
    }


    @Override
    public String getCurrTopField() {
        return currTopField.get();
    }
}
